import React, { LegacyRef, useCallback, useState } from 'react';
import './Register.scss';
import { Link } from 'react-router-dom';
import NavBar from '@/components/NavBar/NavBar';
import { Button, Form, Input, Toast } from 'antd-mobile';
import type { FormInstance } from 'antd-mobile/es/components/form';
import useCountdown from '@/hooks/useCountdown';
import { registerAccount, sendCodeThunk } from '@/store/modules/loginStore';
import { useEnhanceDispatch } from '@/hooks';
import { rules } from '@/utils/rules';
import type { CodeLoginParams, PasswordLoginParams, RegisterParams } from '@/type/LoginType';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons';
import { PasswordType } from '@/views/Login/Login';

const Register: React.FunctionComponent = () => {
  const enhanceDispatch = useEnhanceDispatch();
  // 表单组件实例
  const [formInstance] = Form.useForm<LegacyRef<FormInstance> | undefined>();
  // 自定义的倒计时hooks
  const { timeId, countdown, start, setStart, subCountdown, setCountdown } = useCountdown(60);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 密码框的类型
  const [passwordType, setPasswordType] = useState<PasswordType>('password');
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>优医问诊 登录</span>), []);
  // 右边插槽内容
  const right = useCallback(() => (<Link to="/login">登录</Link>), []);

  /**
   * 获取验证码的回调函数
   * */
  const handleSendCode = async () => {
    try {
      await enhanceDispatch(sendCodeThunk({ mobile: formInstance.getFieldValue('mobile'), type: 'register' })).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   * @description 点击发送验证码按钮的回调函数
   * */
  const sendCode = () => {
    formInstance.validateFields(['mobile']).then(async result => {
      await handleSendCode();
      subCountdown();
    }).catch(error => {
      const message = error.errorFields[0].errors[0];
      Toast.show(message);
    });
  };

  /**
   * @description 提交表单且数据验证成功后触发的回调函数
   * */
  const handleFinsh = async (values: PasswordLoginParams & CodeLoginParams) => {
    await register(values);
  };

  /**
   * @description 提交表单且数据验证失败后触发的回调函数
   * */
  const handleFinishFailed = (error: any) => {
    const message = error.errorFields[0].errors[0];
    Toast.show(message);
  };


  /**
   * @description 注册账号的回调函数
   * */
  const register = async (registerParams: RegisterParams) => {
    try {
      setLoading(true);
      await enhanceDispatch(registerAccount(registerParams)).unwrap();
      Toast.show({ icon: 'success', content: '注册成功' });
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    } finally {
      setLoading(false);
    }
  };

  /**
   * @description 根据passwordType按需渲染文本框类型
   * */
  const renderPasswordType = useCallback(() => passwordType === 'password' ? <EyeInvisibleOutline fontSize={20} /> : <EyeOutline fontSize={20} />, [passwordType]);


  /**
   * @description 切换密码框类型的回调函数
   * */
  const changePasswordType = useCallback(() => {
    setPasswordType(passwordType === 'password' ? 'text' : 'password');
  }, [passwordType]);

  return (
    <div className="register">
      {/*导航栏组件*/}
      <NavBar back={left()} right={right()}></NavBar>
      {/*注册头部*/}
      <div className="register-header">
        <div className="left">
          <h3>注册账号</h3>
        </div>
      </div>
      {/*注册表单*/}
      <Form mode="card" form={formInstance} hasFeedback={false} onFinish={handleFinsh} onFinishFailed={handleFinishFailed}>
        <Form.Item name="mobile" rules={rules.mobile}>
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item name="code" rules={rules.code} extra={<a onClick={sendCode}>{start ? `${countdown}秒后重新获取` : '发送验证码'}</a>}>
          <Input type="text" placeholder="请输入短信验证码" />
        </Form.Item>

        <Form.Item name="password" rules={rules.password} extra={<span onClick={changePasswordType}>{renderPasswordType()}</span>}>
          <Input type={passwordType} placeholder="请输入密码" />
        </Form.Item>

        <Form.Item className="last">
          <Button loading={loading} color="primary" type="submit">注册</Button>
        </Form.Item>

      </Form>
    </div>
  );
};

export default Register;